package com.ysqcould.mp.task;

import cn.hutool.core.util.ObjectUtil;
import com.ysqcould.allocation.utils.UploadFileUtil;
import com.ysqcould.common.utils.DateUtils;
import com.ysqcould.common.utils.spring.SpringUtils;
import com.ysqcould.mp.domain.MpArticle;
import com.ysqcould.mp.domain.MpInfo;
import com.ysqcould.mp.domain.vo.WxResultBody;
import com.ysqcould.mp.service.IMpArticleService;
import com.ysqcould.mp.service.IMpInfoService;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ysqcould.common.utils.DateUtils.differentDaysByMillisecond;
import static com.ysqcould.mp.utils.CollectUtils.findListEx;

/**
 * 文章采集定时任务
 * @author jcd
 */
public class CollectTask {
       public static void CollectTask(){
           /**
            * 获取数据库添加的公众号
            */
           IMpInfoService iMpInfoService = SpringUtils.getBean(IMpInfoService.class);
           MpInfo info=new MpInfo();
           final List<MpInfo> infoList = iMpInfoService.selectMpInfoList(info);
           infoList.forEach(p->{
               String pageNo="1";
               collectArticle(p,pageNo);
               sleep();
           });
       }

    /**
     * 递归获取文章
     * @param p
     */
    private  static void collectArticle(MpInfo p,String pageNo) {
        WxResultBody<List<Map>> resultBody = findListEx(pageNo, p.getFakeid());
        if (resultBody.getBase_resp().getRet()==0){
            System.out.println("开始采集文章数据");
            System.out.println("采集的公众号"+p.getNickname());
          List<Map>list=resultBody.getApp_msg_list();
          if (ObjectUtil.isNotEmpty(list)){
              addArticle(list,p);

          }
        }else {
            throw new RuntimeException("接口异常");
        }
    }

    /**
     * 获取list之后，主程序休眠10s
     */
    private  static void sleep(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将采集的文章数据添加到数据库
     * @param list
     */
    private static void addArticle(List<Map> list,MpInfo p) {
        IMpArticleService service = SpringUtils.getBean(IMpArticleService.class);
        final String date = DateUtils.getMonth();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (Map map: list) {
            if (p.getCode().equals(2)){
                if (!differentDay(map)){
                    return;
                }
            }else {
                if (needStopRecursionFetch(map,date)){
                    return;
                }
            }
            MpArticle mpArticle = new MpArticle();
            mpArticle.setAid(map.get("aid").toString());
            mpArticle.setAppmsgid(map.get("appmsgid").toString());
            mpArticle.setTitle(map.get("title").toString());
            mpArticle.setArticleCreateTime(LocalDateTime.ofEpochSecond(Long.parseLong(map.get("create_time").toString()), 0, ZoneOffset.ofHours(8)));
            mpArticle.setArticleUpdateTime(LocalDateTime.ofEpochSecond(Long.parseLong(map.get("update_time").toString()), 0, ZoneOffset.ofHours(8)));
            mpArticle.setLink(map.get("link").toString());
            mpArticle.setMpInfoId(p.getNickname());
            // 微信官方图片做了防盗链，不可直接引用展示，因此保存到oss
            mpArticle.setCoverUrl(UploadFileUtil.uploadUrlImage(map.get("cover").toString()));
            mpArticle.setDigest(map.get("digest").toString());
            mpArticle.setPaySubscribe(Long.valueOf(map.get("is_pay_subscribe").toString()));
            service.insertMpArticle(mpArticle);
        }
    }

    /**
     * 是否将文章添加进数据库
     * @param map
     * @param startDate
     * @return
     */
    private static boolean needStopRecursionFetch(Map map, String startDate) {
        if (!CollectionUtils.isEmpty(map)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String createDate = sdf.format(new Date(Long.parseLong(map.get("create_time").toString()) * 1000));
                // 开始区间比 文章创建时间 大，即可停止采集
                return createDate.compareTo(startDate) <= 1;
        }
        return false;
    }

    /**
     * 获取相隔一天的文章
     * @param map
     * @return
     */
    private static boolean differentDay(Map map){
        boolean bf=false;
        if (!CollectionUtils.isEmpty(map)){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            final Date date;
            final Date time;
            try {
                date = sdf.parse(DateUtils.getDate());
                time = sdf.parse(map.get("create_time").toString());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            final int days = differentDaysByMillisecond(time, date);
             if (days==1){
                 bf=true;
             }else {
                 bf=false;
             }
        }
      return bf;
    }
}
